import {
	Button,
	Collapse,
	Form,
	Row,
	Col,
	Input,
	Select,
	Upload,
	Cascader,
	TreeSelect,
	message,
	DatePicker,
	Popconfirm,
} from 'antd'
import React, {memo, useState, useEffect, useRef} from 'react'
import {history, connect, useModel} from 'umi'
import moment from 'moment'
import 'moment/locale/zh-cn'

// 可编辑表格
import type {
	ActionType,
	EditableFormInstance,
	ProColumns,
} from '@ant-design/pro-components'
import {EditableProTable} from '@ant-design/pro-components'

import styles from './index.less'

import {
	getAllCitysPermission,
	getOnlydept,
	processRecordSave,
} from '@/service/common/index'
import {getDict} from '@/service/common/dict'
import {getBusinessCode} from '@/service/purchase/common'
import {uploadMoreProps, getPublicDownloadUrl} from '@/service/common/upload'

import {
	getListDetailed,
	addInitiation,
	editInitiation,
	viewInitiation,
	getIsProcessOpen,
	processAdd,
	relaunchFlow,
	auditFlow,
	processSaveTemporary,
} from '@/service/purchase/initiation'

import {getUseList} from '@/service/system/user'

import {translateDataToTree, getEditTableSelect} from '@/utils/common/index'

import {formatDate} from '@/utils/common/dateFilter'
import {twoDecimalPattern} from '@/utils/common/validator'
import OperationRecord from '@/components/OperationRecord'
import Examine from '@/components/Examine'

const {Panel} = Collapse
const {TextArea} = Input

type TreeItem = {
	id: string
	parentId: number
	name: string
	children?: Array<TreeItem>
}[]

// 申请部门与项目申请人
const deptAddUserNames = {
	label: 'name',
	value: 'id',
	key: 'id',
}

// 字典
const dictNames = {
	label: 'dictValue',
	value: 'dictKey',
}

// 城市
const cityNames = {
	label: 'name',
	value: 'id',
	children: 'cityInfoList',
}

interface CityOption {
	value: string | number
	label: string
	children?: CityOption[]
}

type DataSourceType = {
	itemName: string
	id: React.Key
	labels?: {
		key: string
		label: string
	}[]
	state?: string
	children?: DataSourceType[]
}

type OtherParams = {
	applyUsername?: string
	applyDeptname?: string
	principalName?: string
	costsNames?: string
	applicantId?: string
	applyProvincename?: string
	applyProvinceid?: string
	applyCityid?: string
	applyCityname?: string
	cityId?: string
}

const add = memo(
	(props: {
		user: {
			userId: string
			userName: string
			orgId: string | number
			permissionID: any
		}
		global: {currentRoute: any}
		dispatch: any
		location: any
	}) => {
		const {initialState} = useModel('@@initialState')
		const {permissionID} = initialState || {}
		const {dispatch} = props
		const {currentRoute} = props.global
		const {userId, userName, orgId} = props.user
		// 项目申请人
		const [userList, setApplyUser] = useState<any[]>([])
		// 城市
		const [citysList, setCitysList] = useState<CityOption[]>([])
		// 申请部门
		const [deptList, setDeptList] = useState<TreeItem>([])
		const [dict, setDict] = useState<any>({
			category: [],
			purchase_costs_type: [],
			purchase_costitem_type: [],
		})
		const [fileList, setFileList] = useState<any>([])
		const [type, setType] = useState<string>()
		const [form] = Form.useForm<any>()
		const [otherParams, setOtherParams] = useState<OtherParams>({})
		const [budget, setBudget] = useState<any>(0)
		const [budgetSurplus, setBudgetSurplus] = useState<any>(0)
		const examineRef = useRef<any>(null)
		// 可编辑表格
		const actionRef = useRef<ActionType>()
		const editorFormRef = useRef<EditableFormInstance<DataSourceType>>()
		const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([])
		const [costitemList, setCostitemList] = useState<
			readonly DataSourceType[]
		>([])
		const [processOpen, setProcessOpen] = useState<number>(0)
		const [auditStatus, setAuditStatus] = useState<string>('0')
		const [instanceId, setInstanceId] = useState<string>()
		const [newApplyTime, setNewApplyTime] = useState('')

		// 初始化-项目编码
		const onCodeFun = () => {
			getBusinessCode({businessType: 1})
				.then((res: any) => {
					if (res?.success) {
						form.setFieldsValue({projectNo: res?.data})
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}

		// 初始化-流程是否激活
		const getIsProcessOpenFun = () => {
			getIsProcessOpen({businessType: 1})
				.then((res: any) => {
					if (res?.success) {
						setProcessOpen(() => res?.data)
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}

		// 初始化-城市
		// const getCitysFun = () => {
		// 	getAllCitys().then((res: any) => {
		// 		if (res?.data) {
		// 			setCitysList(() => res.data)
		// 		}
		// 	})
		// }
		// 初始化-城市
		const getCitysFun = () => {
			const d = {
				permission: permissionID,
				orgId,
			}
			getAllCitysPermission(d).then((res: any) => {
				if (res?.data) {
					setCitysList(() => res.data)
				}
			})
		}

		// 初始化-申请部门
		const getOnlydeptFun = () => {
			getOnlydept({merchantId: orgId}).then((res: any) => {
				if (res?.data) {
					const list = translateDataToTree(res.data)
					setDeptList(list as unknown as TreeItem)
				}
			})
		}

		// 初始化-立项明细列表
		const getList = () => {
			const {id} = props.location.query
			getListDetailed({applycostId: id}).then((res: any) => {
				if (res?.success) {
					setCostitemList(() => res?.data)
					form.setFieldsValue({
						costitemList: res?.data,
					})
				}
			})
		}

		// 初始化-项目申请人
		const getApplyUser = () => {
			getUseList({merchantId: orgId}).then((res: any) => {
				if (res?.data) {
					setApplyUser(() => res.data)
				}
			})
		}

		// 初始化-附件列表
		const getFileList = (ids: any) => {
			getPublicDownloadUrl(ids).then((res: any) => {
				if (res?.success) {
					const list = res?.data.map((item: any) => ({
						name: item?.filename,
						status: 'done',
						url: item?.url,
						response: {
							data: {
								id: item?.id,
							},
						},
					}))
					setFileList(() => [...list])
				}
			})
		}
		// 初始化-详情数据
		const getView = (id: string) => {
			viewInitiation(id).then((res: any) => {
				if (res?.success) {
					setAuditStatus(() => res?.data?.auditStatus)
					setNewApplyTime(res?.data?.applyTime)
					setInstanceId(() => res?.data?.instanceId)
					delete res?.data?.applyTime
					form.setFieldsValue({
						...res.data,
						startTime: res?.data?.startTime
							? moment(res?.data?.startTime)
							: null,
						finishTime: res?.data?.finishTime
							? moment(res?.data?.finishTime)
							: null,
						applyCityid: res?.data?.applyCityid
							? [res.data.applyProvinceid, res.data.applyCityid]
							: null,
					})
					setOtherParams({
						...otherParams,
						applyUsername: res.data.applyUsername,
						applyDeptname: res.data.applyDeptname,
						principalName: res.data.principalName,
						costsNames: res.data.costsNames,
						applicantId: res.data.applicantId,
						applyProvincename: res.data.applyProvincename,
						applyProvinceid: res.data.applyProvinceid,
						applyCityid: res.data.applyCityid,
						applyCityname: res.data.applyCityname,
						cityId: res.data.cityId,
					})
					setBudget(() => res?.data?.budget)
					setBudgetSurplus(() => res?.data?.budgetSurplus)
					if (res?.data?.attachmentList.length) {
						getFileList(res?.data?.attachmentList)
					}
				}
			})
		}

		useEffect(() => {
			getOnlydeptFun()
			getApplyUser()
		}, [orgId])
		useEffect(() => {
			if (newApplyTime) {
				if (
					auditStatus &&
					auditStatus === '4' &&
					window.location.href.includes('edit') &&
					processOpen === 1
				) {
					form.setFieldsValue({
						applyTime: moment(
							moment().format('YYYY-MM-DD HH:mm:ss'),
						),
					})
				} else {
					form.setFieldsValue({
						applyTime: moment(newApplyTime),
					})
				}
			}
		}, [auditStatus, processOpen, newApplyTime])

		useEffect(() => {
			if (permissionID) {
				getCitysFun()
			}
		}, [permissionID])

		// 根据路由判断当前页面状态
		useEffect(() => {
			const {id} = props.location.query
			getIsProcessOpenFun()

			getDict(
				{
					dictKeys: [
						'category',
						'purchase_costs_type',
						'purchase_costitem_type',
					],
				},
				(res: any) => {
					setDict(res)
				},
			)
			if (id) {
				getView(id)
				getList()
			}
			const hrefs = window.location.href
			if (hrefs.includes('view')) {
				setType('view')
			} else if (hrefs.includes('add')) {
				onCodeFun()
				setType('add')
				form.setFieldsValue({
					applicantName: userName,
					applyTime: moment(moment().format('YYYY-MM-DD HH:mm:ss')),
				})
				setOtherParams({
					...otherParams,
					applicantId: userId,
				})
			} else if (hrefs.includes('edit')) {
				setType('edit')
			} else {
				setType('process')
			}
			// form.setFieldsValue({
			// 	...form,
			// })
		}, [])

		const customizeHeader = (value: string) => (
			<div>
				<div className={styles.tip} />
				{value}
			</div>
		)
		const goback = () => {
			dispatch({
				type: 'global/deleteTabs',
				payload: currentRoute,
			})
			const {goPath, pathParams} = props.location.query
			if (goPath) {
				if (pathParams) {
					history.push({
						pathname: goPath,
						query: {
							id: pathParams,
						},
					})
				} else {
					history.push({
						pathname: goPath,
					})
				}
			} else {
				history.push({
					pathname: '/purchase/initiation',
				})
			}
		}

		// 数据及审核提交
		const submit = async (btnType: string) => {
			const formData = await form.validateFields()
			const {id} = props.location.query
			// 附件处理
			const attachmentList = formData?.attachmentList?.fileList?.map(
				(item: any) => Number(item?.response?.data?.id),
			)
			// 项目开始时间与结束时间处理
			const startTime = formatDate(
				formData.startTime,
				'YYYY-MM-DD HH:mm:ss',
			)
			const finishTime = formatDate(
				formData.finishTime,
				'YYYY-MM-DD HH:mm:ss',
			)
			const applyTime = moment(formData.applyTime).format(
				'YYYY-MM-DD HH:mm:ss',
			)
			if (!costitemList?.length) {
				message.error('至少添加一条立项明细！')
				return false
			}
			const totalAmount = costitemList
				?.map((item: any) => Number(item.totalAmount))
				?.reduce((prev: any, curr: any) => Number(prev) + Number(curr))
			const init = parseInt(totalAmount.toString(), 10)
			if (init.toString()?.length > 8) {
				message.error(
					'立项明细数据过大，请重新添加，总计整数部分不能超过8位数！',
				)
				return false
			}
			// 立项明细处理
			const list = costitemList?.map((item: any) => {
				const newItem = item
				const itemNames = dict?.purchase_costitem_type?.filter(
					(i: any) => i.dictKey === item.itemTypes,
				)[0]?.dictValue
				newItem.itemNames = itemNames
				if (!item?.updateUser) {
					delete newItem.id
				}
				return newItem
			})
			const submitParams = {
				...formData,
				...otherParams,
				principalName: formData?.principalName,
				startTime,
				finishTime,
				applyTime,
				costitemList: list,
				attachmentList: attachmentList || [],
				budget,
				budgetSurplus,
			}
			if (btnType === 'submit') {
				if (auditStatus === '9' || !id) {
					const queryData = {
						...submitParams,
					}
					if (id) {
						queryData.id = id
					}
					if (processOpen === 1) {
						// 流程自动发起
						processAdd(queryData)
							.then((res) => {
								if (res?.success) {
									message.success(res.msg)
									goback()
								}
							})
							.catch((err) => {
								message.error(err)
							})
					} else {
						// 流程未开启默认新增
						addInitiation(queryData)
							.then((res) => {
								if (res?.success) {
									message.success(res.msg)
									goback()
								}
							})
							.catch((err) => {
								message.error(err)
							})
					}
				} else if (processOpen === 1 && auditStatus === '4') {
					// 流程重新发起
					relaunchFlow(id, submitParams)
						.then((res: {msg: string; success: boolean}) => {
							if (res?.success) {
								message.success(res.msg)
								goback()
							}
						})
						.catch((err: any) => {
							message.error(err)
						})
				} else {
					// 流程未开启默认编辑
					editInitiation(id, submitParams)
						.then((res) => {
							if (res?.success) {
								message.success(res.msg)
								goback()
							}
						})
						.catch((err) => {
							message.error(err)
						})
				}
			}
			if (btnType === 'save') {
				const queryData = {
					...submitParams,
				}
				if (id) {
					queryData.id = id
				}
				processSaveTemporary(queryData)
					.then((res) => {
						if (res?.success) {
							message.success(res.msg)
							goback()
						}
					})
					.catch((err) => {
						message.error(err)
					})
			}

			return true
		}

		/** 审核 */
		const onCompleteTask = async (pass: string) => {
			const examineData = await examineRef.current.getData()
			if (examineData?.url) {
				const flowParams = {
					message: examineData?.message,
					businessId: props?.location?.query?.id,
					instanceId,
					pass,
					attachmentList: examineData?.url?.split(','),
				}
				if (pass === '3') {
					flowParams.message = JSON.stringify(examineData)
				}
				auditFlow(flowParams)
					.then((res: {msg: string; success: boolean}) => {
						if (res?.success) {
							message.success(res.msg)
							if (pass === '3') {
								processRecordSave({
									bizType: 1,
									bizNo: props?.location?.query?.id,
									processId: instanceId,
								})
							}
							goback()
						}
					})
					.catch((err: any) => {
						message.error(err)
					})
			} else {
				message.warning('请上传附件')
			}
		}
		// 项目申请人变化
		const onApplyUserChange = (value: string, option: any) => {
			setOtherParams({
				...otherParams,
				applyUsername: option?.name,
			})
		}

		// 申请部门变化
		const onApplyDeptChange = (value: string, option: any) => {
			setOtherParams({
				...otherParams,
				applyDeptname: option[0],
			})
		}

		// 城市变化
		const onCitysChange = (value: any, selectedOptions: any) => {
			if (value) {
				setOtherParams({
					...otherParams,
					applyProvincename: selectedOptions[0].name,
					applyProvinceid: selectedOptions[0].id,
					applyCityid: selectedOptions[1].id,
					applyCityname: selectedOptions[1].name,
					cityId: selectedOptions[1].id,
				})
			}
		}

		// 费用类型变化
		const onCostsTypesChange = (value: any, option: any) => {
			setOtherParams({
				...otherParams,
				costsNames: option?.dictValue,
			})
		}
		// 可编辑表格
		const proColumns: ProColumns<DataSourceType>[] = [
			{
				title: (
					<>
						<span className="required">* </span> 项目明细名称
					</>
				),
				dataIndex: 'itemName',
				formItemProps: {
					rules: [
						{
							required: true,
							message: '此项为必填项',
						},
					],
				},
			},
			{
				title: (
					<>
						<span className="required">* </span> 项目明细品类
					</>
				),
				dataIndex: 'itemTypes',
				valueType: 'select',
				valueEnum: getEditTableSelect(dict?.purchase_costitem_type),
				formItemProps: {
					rules: [
						{
							required: true,
							message: '此项为必填项',
						},
					],
				},
			},
			{
				title: (
					<>
						<span className="required">* </span> 明细预算数量
					</>
				),
				dataIndex: 'quantity',
				formItemProps: {
					rules: [
						{
							required: true,
							pattern: twoDecimalPattern,
							message: '明细预算数量格式不正确',
						},
					],
				},
			},
			{
				title: (
					<>
						<span className="required">* </span> 明细预算单价
					</>
				),
				dataIndex: 'price',
				formItemProps: {
					rules: [
						{
							required: true,
							pattern: twoDecimalPattern,
							message: '明细预算单价不正确',
						},
					],
				},
			},
			{
				title: (
					<>
						<span className="required">* </span> 明细预算金额
					</>
				),
				dataIndex: 'totalAmount',
				editable: false,
				formItemProps: {
					rules: [
						{
							required: true,
							pattern: twoDecimalPattern,
							message: '明细预算金额不正确',
						},
					],
				},
			},
			{
				title: '操作',
				valueType: 'option',
				width: 200,
				hideInTable: type === 'view' || type === 'process',
				render: (text: any, record: any, _: any, action: any) => [
					<Button
						type="link"
						key="editable"
						size="small"
						onClick={() => {
							action?.startEditable?.(record.id)
						}}>
						编辑
					</Button>,
					<Popconfirm
						placement="topLeft"
						title="你确定要删除这条数据吗？"
						onConfirm={() => {
							setCostitemList(
								costitemList.filter(
									(item: any) => item.id !== record.id,
								),
							)
						}}
						okText="确定"
						cancelText="取消">
						<Button type="link" key="delete">
							删除
						</Button>
					</Popconfirm>,
				],
			},
		]
		// 计算精度
		const multiply = (num1: any, num2: any) => {
			let total: any = num1 * num2
			if (
				JSON.stringify(num1).indexOf('.') !== -1 ||
				JSON.stringify(num2).indexOf('.') !== -1
			) {
				const floatNum1 = JSON.stringify(num1).split('.')
				const floatNum2 = JSON.stringify(num2).split('.')
				// 获取小数点的位数，如果没有小数点则改为0
				const floatNum3 =
					floatNum1.length === 2 ? floatNum1[1].length : 0
				const floatNum4 =
					floatNum2.length === 2 ? floatNum2[1].length : 0
				// 将小数点位数相加
				const index = floatNum3 + floatNum4
				// 取近似值Math.round
				total = Math.round(total * 10 ** index) / 10 ** index
			}
			return total
		}
		// 获取动态表格数据
		const getCostitemList = (list: any) => {
			const data = list?.map((item: any) => {
				const newItem = item
				newItem.itemNames = dict?.purchase_costitem_type?.filter(
					(i: any) => i.dictKey === newItem.itemTypes,
				)?.[0].dictValue
				const totalPrice = multiply(newItem.quantity, newItem.price)
				newItem.totalAmount = totalPrice.toFixed(2)
				return newItem
			})
			setCostitemList(() => data)
		}

		useEffect(() => {
			const list = costitemList
				?.map((item: any) => Number(item?.totalAmount))
				.reduce((prev: any, cur: any) => Number(prev) + Number(cur), 0)
			const cuntAmount = Number(list)?.toFixed(2)
			if (type === 'add' || type === 'edit') {
				setBudget(() => cuntAmount)
				setBudgetSurplus(() => cuntAmount)
				form.setFieldsValue({
					budget: cuntAmount,
					budgetSurplus: cuntAmount,
				})
			}
		}, [costitemList])

		// const disabledFinishTimeDate: RangePickerProps['disabledDate'] = (
		// 	current,
		// ) => {
		// 	return current && current < moment('2023-1-10')
		// }
		// const disabledStartTimeDate: RangePickerProps['disabledDate'] = (
		// 	current,
		// ) => {
		// 	return current && current > moment('2023-1-1')
		// }

		// 设置开始日期不能选择的时间
		const disabledFinishTimeDate = (startValue: any) => {
			const finishTime = form.getFieldValue('finishTime')
			if (!startValue || !finishTime) {
				return false
			}
			return startValue.valueOf() > finishTime.valueOf()
		}

		// 设置结束不能选择的时间
		const disabledStartTimeDate = (endValue: any) => {
			const startTime = form.getFieldValue('startTime')
			if (!endValue || !startTime) {
				return false
			}
			return endValue.valueOf() <= startTime.valueOf()
		}

		return (
			<div className={styles.admittanceAdd}>
				<div className={`${styles.content} ${styles.formDetils}`}>
					{instanceId && (type === 'view' || type === 'process') ? (
						<Examine
							ref={examineRef}
							examineType={type === 'process'}
							orgId={props?.user?.orgId}
							processInstanceId={instanceId}
							required
							bizType={1}
							bizNo={props?.location?.query?.id}
						/>
					) : (
						''
					)}

					<Collapse
						defaultActiveKey={['1', '2', '3']}
						ghost
						expandIconPosition="end">
						<Panel header={customizeHeader('基础信息')} key="1">
							<Form
								form={form}
								name="basic"
								layout="horizontal"
								labelCol={{flex: '120px'}}
								labelAlign="right"
								labelWrap
								initialValues={{remember: true}}
								autoComplete="off"
								disabled={
									type === 'view' || type === 'process'
								}>
								<Row gutter={12}>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="项目编码"
											name="projectNo"
											rules={[{required: true}]}>
											<Input
												placeholder="请输入"
												disabled
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="项目名称"
											name="projectName"
											rules={[{required: true}]}>
											<Input
												placeholder="请输入"
												maxLength={30}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										{type === 'view' ? (
											<Form.Item
												label="项目申请人"
												name="applyUsername"
												rules={[{required: true}]}>
												<Input placeholder="请选择" />
											</Form.Item>
										) : (
											<Form.Item
												label="项目申请人"
												name="applyUserid"
												rules={[{required: true}]}>
												<Select
													placeholder="请选择"
													showSearch
													filterOption={(
														input,
														option,
													) =>
														(
															option?.name ?? ''
														).includes(input)
													}
													optionFilterProp="children"
													options={userList}
													fieldNames={
														deptAddUserNames
													}
													onChange={onApplyUserChange}
												/>
											</Form.Item>
										)}
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										{type === 'view' ? (
											<Form.Item
												label="申请部门"
												name="applyDeptname"
												rules={[{required: true}]}>
												<Input placeholder="请选择" />
											</Form.Item>
										) : (
											<Form.Item
												label="申请部门"
												name="applyDeptid"
												rules={[{required: true}]}>
												<TreeSelect
													showSearch
													treeNodeFilterProp="name"
													style={{width: '100%'}}
													placeholder="请选择"
													fieldNames={
														deptAddUserNames
													}
													treeDefaultExpandAll
													treeData={deptList}
													onChange={onApplyDeptChange}
												/>
											</Form.Item>
										)}
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="城市"
											name="applyCityid"
											rules={[{required: true}]}>
											<Cascader
												fieldNames={cityNames}
												options={citysList}
												placeholder="请选择"
												onChange={onCitysChange}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="项目负责人"
											name="principalName"
											rules={[{required: true}]}>
											<Input placeholder="请输入" />
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="项目开始时间"
											name="startTime"
											rules={[{required: true}]}>
											<DatePicker
												format="YYYY-MM-DD"
												disabledDate={
													disabledFinishTimeDate
												}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="项目结束时间"
											name="finishTime"
											rules={[{required: true}]}>
											<DatePicker
												format="YYYY-MM-DD"
												disabledDate={
													disabledStartTimeDate
												}
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="费用类型"
											name="costsTypes"
											rules={[{required: true}]}>
											<Select
												showSearch
												filterOption={(input, option) =>
													(
														option?.dictValue ?? ''
													).includes(input)
												}
												placeholder="请选择"
												options={
													dict.purchase_costs_type
												}
												onChange={onCostsTypesChange}
												fieldNames={dictNames}
											/>
										</Form.Item>
									</Col>
									<Col sm={{span: 24}} />
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="预算金额"
											name="budget">
											{budget || 0}元
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="预算剩余金额"
											name="budgetSurplus">
											{budgetSurplus || 0}元
										</Form.Item>
									</Col>
									<Col sm={{span: 24}} />
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="项目需求描述"
											name="requirDesc"
											rules={[{required: true}]}>
											<TextArea
												maxLength={100}
												placeholder="请输入（最多100个字）"
												autoSize={{
													minRows: 3,
													maxRows: 6,
												}}
											/>
										</Form.Item>
									</Col>
									<Col sm={{span: 24}} />
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="申请人"
											name="applicantName">
											<Input
												placeholder="请输入"
												disabled
											/>
										</Form.Item>
									</Col>
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="申请时间"
											name="applyTime">
											{processOpen === 1 ? (
												<DatePicker
													format="YYYY-MM-DD HH:mm:ss"
													disabled
												/>
											) : (
												<DatePicker
													format="YYYY-MM-DD"
													allowClear={false}
													disabled={type === 'view'}
												/>
											)}
										</Form.Item>
									</Col>
									<Col sm={{span: 24}} />
									<Col
										sm={{span: 24}}
										md={{span: 12}}
										lg={{span: 8}}>
										<Form.Item
											label="附件上传"
											name="attachmentList">
											<Upload
												{...uploadMoreProps(
													'initiation',
													0,
													fileList,
													(
														t: string,
														flist: any,
														file: any,
													) => {
														if (t === 'sizeBig') {
															const list =
																flist?.filter(
																	(
																		item: any,
																	) =>
																		item.id.toString() !==
																		file.id.toString(),
																)
															setFileList(
																() => list,
															)
															return false
														}
														if (t === 'error') {
															const list =
																flist?.filter(
																	(
																		item: any,
																	) =>
																		item.id.toString() !==
																		file.id.toString(),
																)
															setFileList(
																() => list,
															)
														} else if (
															[
																'done',
																'setData',
															].includes(t)
														) {
															setFileList(
																() => flist,
															)
														} else if (
															t === 'remove'
														) {
															const list =
																flist?.filter(
																	(
																		item: any,
																	) =>
																		item.id.toString() !==
																		file.id.toString(),
																)
															setFileList(
																() => list,
															)
														}
														return true
													},
												)}>
												<Button
													type="primary"
													ghost
													shape="round"
													size="small">
													请选择文件
												</Button>
											</Upload>
										</Form.Item>
									</Col>
									<Col sm={{span: 24}}>
										<div className="uploadTip">
											附件说明：附件最大支持200M，支持格式：PDF、Word、Excel、JPG、PNG、ZIP、RAR
										</div>
									</Col>
								</Row>
							</Form>
						</Panel>
						<Panel header={customizeHeader('立项明细')} key="2">
							<>
								{type === 'edit' || type === 'add' ? (
									<Button
										type="primary"
										ghost
										size="small"
										style={{marginBottom: '12px'}}
										onClick={() => {
											actionRef.current?.addEditRecord?.({
												id: `ID${(
													Math.random() * 100000000
												).toFixed(0)}`,
											})
										}}>
										新增
									</Button>
								) : (
									''
								)}
								<EditableProTable<DataSourceType>
									bordered
									rowKey="id"
									key="id"
									actionRef={actionRef}
									editableFormRef={editorFormRef}
									maxLength={5}
									// 关闭默认的新建按钮
									recordCreatorProps={false}
									columns={proColumns}
									value={costitemList}
									onChange={(value: any) =>
										getCostitemList(value)
									}
									editable={{
										form,
										editableKeys,
										onSave: async () => true,
										onChange: setEditableRowKeys,
										actionRender: (row, config, dom) => [
											dom.save,
											dom.cancel,
										],
									}}
								/>
							</>
						</Panel>
						{type === 'view' ? (
							<Panel
								header={customizeHeader('操作记录')}
								key="3"
								forceRender>
								<OperationRecord
									businessId={props.location.query?.id}
									businessType={31}
								/>
							</Panel>
						) : (
							''
						)}
					</Collapse>
					<div className={styles.wrap}>
						<Button onClick={goback}>取消</Button>
						{type !== 'view' && type !== 'process' ? (
							<>
								<Button
									type="primary"
									htmlType="submit"
									onClick={() => submit('save')}>
									保存
								</Button>
								<Button
									type="primary"
									htmlType="submit"
									onClick={() => submit('submit')}>
									提交
								</Button>
							</>
						) : null}

						{type === 'process' ? (
							<>
								<Button
									type="primary"
									htmlType="submit"
									onClick={() => {
										onCompleteTask('1')
									}}>
									同意
								</Button>
								<Button
									onClick={() => {
										onCompleteTask('2')
									}}>
									驳回
								</Button>
								<Button
									onClick={() => {
										onCompleteTask('3')
									}}>
									拒绝
								</Button>
							</>
						) : (
							''
						)}
					</div>
				</div>
			</div>
		)
	},
)
export default connect(({global, user}: any) => ({global, user}))(add)
